package com.example.movie_control;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.util.*;

public class CinemaSystem {
    private Map<String, User> userMap = new HashMap<>();
    private Map<String, Hall> hallMap = new HashMap<>();
    private Map<String, Movie> movieMap = new HashMap<>();
    private Map<String, Schedule> scheduleMap = new HashMap<>();
    private Map<String, TicketOrder> orderMap = new HashMap<>();
    private List<String> logList = new ArrayList<>();

    public CinemaSystem() {
        // 初始化影厅
        hallMap.put("GOLD_HALL", new Hall("GOLD_HALL", "黄金厅", 8, 10));
        hallMap.put("SILVER_HALL", new Hall("SILVER_HALL", "白银厅", 10, 12));
        hallMap.put("EMERALD_HALL", new Hall("EMERALD_HALL", "翡翠厅", 7, 8));
        hallMap.put("DIAMOND_HALL", new Hall("DIAMOND_HALL", "钻石厅", 7, 8));
        hallMap.put("GEM_HALL", new Hall("GEM_HALL", "宝石厅", 8, 9));

        // 初始化用户（补充手机号，默认密码123456时强制首登修改）
        userMap.put("admin", new AdminUser("admin", "admin", "ynuinfo#777", "13800138000"));
        userMap.put("m1", new Manager("m1", "m1", "ynuinfo#777", "13900139000"));
        userMap.put("f1", new FrontDesk("f1", "f1", "ynuinfo#777", "13700137000"));

        // 初始化测试数据（示例影片和排片）
        initTestData();
    }

    // 初始化测试数据
    private void initTestData() {
        // 添加测试影片
        movieMap.put("M001", new Movie("M001", "复仇者联盟4", "科幻/冒险", " ", "", 123,9.5));
        movieMap.put("M002", new Movie("M002", "流浪地球3", "科幻/灾难", "沈腾", "", 123,9.6));

        // 添加测试排片
        scheduleMap.put("S001", new Schedule("S001", "M001", "GOLD_HALL",
                LocalDateTime.of(2025, 7, 20, 10, 0), 80.0));
        scheduleMap.put("S002", new Schedule("S002", "M002", "SILVER_HALL",
                LocalDateTime.of(2025, 7, 20, 14, 30), 60.0));
    }

    public User login(String username, String password) {
        for (User user : userMap.values()) {
            if (user.getUsername().equals(username) && user.getPassword().equals(password)) {
                // 校验：若为首次登录（密码重置后），强制修改密码
                if (user.isFirstLogin()) {
                    System.out.println("密码为初始密码，请立即修改！");
                    Scanner scanner = new Scanner(System.in);
                    while (true) {
                        System.out.print("请输入新密码：");
                        String newPwd = scanner.nextLine();
                        System.out.print("请确认新密码：");
                        String confirmPwd = scanner.nextLine();
                        if (newPwd.equals(confirmPwd) && !newPwd.equals("123456")) {
                            user.changePassword(newPwd);
                            user.setFirstLogin(false);
                            logOperation("用户 " + username + " 首次登录修改密码");
                            break;
                        } else {
                            System.out.println("两次输入不一致或密码为初始密码，请重新输入！");
                        }
                    }
                }
                return user;
            }
        }
        return null;
    }

    public void startSystem() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("=== 影院票务管理系统 ===");

        while (true) {
            System.out.println("1. 登录");
            System.out.println("0. 退出系统");
            System.out.print("请选择操作：");
            int choice = scanner.nextInt();
            scanner.nextLine();

            if (choice == 0) {
                System.out.println("感谢使用影院票务管理系统！");
                break;
            } else if (choice == 1) {
                System.out.print("请输入用户名：");
                String username = scanner.nextLine();
                System.out.print("请输入密码：");
                String password = scanner.nextLine();

                User user = login(username, password);
                if (user != null) {
                    System.out.println("欢迎回来，" + user.getUsername() + "！");
                    handleUserMenu(user, scanner);
                } else {
                    System.out.println("用户名或密码错误！");
                }
            } else {
                System.out.println("无效选择，请重新输入！");
            }
        }
    }

    private void handleUserMenu(User user, Scanner scanner) {
        while (true) {
            user.showMenu(this);
            System.out.print("请选择操作：");
            int choice = scanner.nextInt();
            scanner.nextLine();

            if (choice == 0) {
                System.out.println("已退出登录！");
                break;
            }

            if (user instanceof AdminUser) {
                handleAdminMenu((AdminUser) user, choice, scanner);
            } else if (user instanceof Manager) {
                handleManagerMenu((Manager) user, choice, scanner);
            } else if (user instanceof FrontDesk) {
                handleFrontDeskMenu((FrontDesk) user, choice, scanner);
            } else {
                System.out.println("未知用户类型！");
            }
        }
    }

    private void handleAdminMenu(AdminUser admin, int choice, Scanner scanner) {
        switch (choice) {
            case 1:
                System.out.println("=== 用户管理 ===");
                System.out.println("1. 添加用户");
                System.out.println("2. 删除用户");
                System.out.println("3. 查询用户（ID/用户名）");
                System.out.println("4. 列出所有用户");
                System.out.println("5. 修改用户信息（类型/手机号）");
                int subChoice = scanner.nextInt();
                scanner.nextLine();

                if (subChoice == 1) {
                    System.out.print("输入用户ID：");
                    String userId = scanner.nextLine();
                    System.out.print("输入用户名：");
                    String username = scanner.nextLine();
                    System.out.print("输入用户类型（admin/manager/frontdesk）：");
                    String userType = scanner.nextLine();
                    System.out.print("输入手机号：");
                    String phone = scanner.nextLine();
                    System.out.print("输入密码（默认123456）：");
                    String password = scanner.nextLine();
                    if (password.isEmpty()) password = "123456";

                    User newUser = null;
                    switch (userType) {
                        case "admin":
                            newUser = new AdminUser(userId, username, password, phone);
                            break;
                        case "manager":
                            newUser = new Manager(userId, username, password, phone);
                            break;
                        case "frontdesk":
                            newUser = new FrontDesk(userId, username, password, phone);
                            break;
                        default:
                            System.out.println("无效用户类型！");
                            return;
                    }

                    userMap.put(userId, newUser);
                    logOperation("管理员 " + admin.getUsername() + " 添加用户 " + userId);
                    System.out.println("用户添加成功！");
                } else if (subChoice == 2) {
                    System.out.print("输入要删除的用户ID：");
                    String userId = scanner.nextLine();
                    if (userId.equals("admin")) {
                        System.out.println("禁止删除超级管理员！");
                        return;
                    }

                    if (userMap.containsKey(userId)) {
                        userMap.remove(userId);
                        logOperation("管理员 " + admin.getUsername() + " 删除用户 " + userId);
                        System.out.println("用户删除成功！");
                    } else {
                        System.out.println("用户不存在！");
                    }
                } else if (subChoice == 3) {
                    System.out.print("输入查询方式（1-用户ID/2-用户名）：");
                    int queryType = scanner.nextInt();
                    scanner.nextLine();
                    String key = scanner.nextLine();
                    boolean found = false;
                    for (User user : userMap.values()) {
                        if ((queryType == 1 && user.getUserId().equals(key))
                                || (queryType == 2 && user.getUsername().equals(key))) {
                            printUserInfo(user);
                            found = true;
                        }
                    }
                    if (!found) System.out.println("用户不存在！");
                } else if (subChoice == 4) {
                    System.out.println("=== 所有用户列表 ===");
                    for (User user : userMap.values()) {
                        printUserInfo(user);
                    }
                } else if (subChoice == 5) {
                    System.out.print("输入要修改的用户ID：");
                    String userId = scanner.nextLine();
                    User user = userMap.get(userId);
                    if (user == null) {
                        System.out.println("用户不存在！");
                        return;
                    }

                    System.out.println("当前用户信息：");
                    printUserInfo(user);

                    System.out.println("1. 修改用户类型");
                    System.out.println("2. 修改手机号");
                    int modifyChoice = scanner.nextInt();
                    scanner.nextLine();

                    if (modifyChoice == 1) {
                        System.out.print("输入新用户类型（admin/manager/frontdesk）：");
                        String newType = scanner.nextLine();
                        // 实际项目中可能需要重新创建用户对象
                        System.out.println("用户类型修改功能待完善！");
                    } else if (modifyChoice == 2) {
                        System.out.print("输入新手机号：");
                        String newPhone = scanner.nextLine();
                        user.setPhone(newPhone);
                        logOperation("管理员 " + admin.getUsername() + " 修改用户 " + userId + " 的手机号");
                        System.out.println("手机号修改成功！");
                    }
                }
                break;

            case 2:
                System.out.println("=== 密码管理 ===");
                System.out.println("1. 修改自身密码");
                System.out.println("2. 重置非管理员密码");
                int pwdChoice = scanner.nextInt();
                scanner.nextLine();

                if (pwdChoice == 1) {
                    System.out.print("输入原密码：");
                    String oldPwd = scanner.nextLine();
                    if (!admin.getPassword().equals(oldPwd)) {
                        System.out.println("原密码错误！");
                        break;
                    }
                    System.out.print("输入新密码：");
                    String newPwd = scanner.nextLine();
                    admin.changePassword(newPwd);
                    logOperation("管理员 " + admin.getUsername() + " 修改自身密码");
                    System.out.println("密码修改成功！");
                } else if (pwdChoice == 2) {
                    System.out.print("输入要重置密码的用户ID：");
                    String userId = scanner.nextLine();
                    if (userId.equals("admin")) {
                        System.out.println("禁止重置超级管理员密码！");
                        break;
                    }

                    User targetUser = userMap.get(userId);
                    if (targetUser == null) {
                        System.out.println("用户不存在！");
                        break;
                    }

                    System.out.print("输入新密码（默认123456）：");
                    String newPwd = scanner.nextLine();
                    if (newPwd.isEmpty()) newPwd = "123456";

                    targetUser.changePassword(newPwd);
                    targetUser.setFirstLogin(true); // 强制下次登录修改密码
                    logOperation("管理员 " + admin.getUsername() + " 重置用户 " + userId + " 的密码");
                    System.out.println("密码重置成功！");
                }
                break;

            default:
                System.out.println("无效选择！");
        }
    }

    private void handleManagerMenu(Manager manager, int choice, Scanner scanner) {
        switch (choice) {
            case 1:
                System.out.println("=== 排片管理 ===");
                System.out.println("1. 添加场次");
                System.out.println("2. 修改场次");
                System.out.println("3. 删除场次");
                int scheduleChoice = scanner.nextInt();
                scanner.nextLine();

                if (scheduleChoice == 1) {
                    System.out.print("输入影片ID：");
                    String movieId = scanner.nextLine();
                    if (!movieMap.containsKey(movieId)) {
                        System.out.println("影片不存在！");
                        break;
                    }

                    System.out.print("输入影厅ID：");
                    String hallId = scanner.nextLine();
                    if (!hallMap.containsKey(hallId)) {
                        System.out.println("影厅不存在！");
                        break;
                    }

                    System.out.print("输入放映时间（格式：yyyy-MM-dd HH:mm）：");
                    String timeStr = scanner.nextLine();
                    LocalDateTime showTime = LocalDateTime.parse(timeStr, java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));

                    // 校验：影厅时间冲突
                    for (Schedule s : scheduleMap.values()) {
                        if (s.getHallId().equals(hallId) &&
                                !showTime.plusMinutes(movieMap.get(movieId).getDuration()).isBefore(s.getShowTime()) &&
                                !showTime.isAfter(s.getShowTime().plusMinutes(movieMap.get(s.getMovieId()).getDuration()))) {
                            System.out.println("该影厅在此时段已有排片！");
                            return;
                        }
                    }

                    // 校验：影厅时间冲突
                    for (Schedule s : scheduleMap.values()) {
                        if (s.getHallId().equals(hallId) &&
                                !showTime.plusMinutes(movieMap.get(movieId).getDuration()).isBefore(s.getShowTime()) &&
                                !showTime.isAfter(s.getShowTime().plusMinutes(movieMap.get(s.getMovieId()).getDuration()))) {
                            System.out.println("该影厅在此时段已有排片！");
                            return;
                        }
                    }

                    System.out.print("输入票价：");
                    double price = scanner.nextDouble();
                    scanner.nextLine();


                    String scheduleId = "S" + (scheduleMap.size() + 1);
                    Schedule newSchedule = new Schedule(scheduleId, movieId, hallId, showTime, price);
                    scheduleMap.put(scheduleId, newSchedule);

                    logOperation("经理 " + manager.getUsername() + " 添加场次 " + scheduleId);
                    System.out.println(scheduleId + "场次添加成功！");
                } else if (scheduleChoice == 2) {
                    System.out.print("输入场次ID：");
                    String scheduleId = scanner.nextLine();
                    Schedule oldSchedule = scheduleMap.get(scheduleId);
                    if (oldSchedule == null) {
                        System.out.println("场次不存在！");
                        break;
                    }

                    // 校验：该场次是否有售票
                    boolean hasTicket = false;
                    for (TicketOrder order : orderMap.values()) {
                        if (order.getScheduleId().equals(scheduleId)) {
                            hasTicket = true;
                            break;
                        }
                    }
                    if (hasTicket) {
                        System.out.println("场次已有售票，禁止修改！");
                        break;
                    }

                    System.out.println("当前场次信息：");
                    System.out.println("影片：" + movieMap.get(oldSchedule.getMovieId()).getMovieName());
                    System.out.println("影厅：" + hallMap.get(oldSchedule.getHallId()).getHallName());
                    System.out.println("时间：" + oldSchedule.getShowTime());
                    System.out.println("票价：" + oldSchedule.getPrice());

                    System.out.println("1. 修改放映时间");
                    System.out.println("2. 修改票价");
                    int modifyChoice = scanner.nextInt();
                    scanner.nextLine();

                    if (modifyChoice == 1) {
                        System.out.print("输入新放映时间（格式：yyyy-MM-dd HH:mm）：");
                        String timeStr = scanner.nextLine();
                        LocalDateTime newTime = LocalDateTime.parse(timeStr, java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));

                        // 校验：影厅时间冲突
                        for (Schedule s : scheduleMap.values()) {
                            if (!s.getScheduleId().equals(scheduleId) &&
                                    s.getHallId().equals(oldSchedule.getHallId()) &&
                                    !newTime.plusMinutes(movieMap.get(oldSchedule.getMovieId()).getDuration()).isBefore(s.getShowTime()) &&
                                    !newTime.isAfter(s.getShowTime().plusMinutes(movieMap.get(s.getMovieId()).getDuration()))) {
                                System.out.println("该影厅在此时段已有排片！");
                                return;
                            }
                        }

                        oldSchedule.setShowTime(newTime);
                        logOperation("经理 " + manager.getUsername() + " 修改场次 " + scheduleId + " 的放映时间");
                        System.out.println("放映时间修改成功！");
                    } else if (modifyChoice == 2) {
                        System.out.print("输入新票价：");
                        double newPrice = scanner.nextDouble();
                        scanner.nextLine();
                        oldSchedule.setPrice(newPrice);
                        logOperation("经理 " + manager.getUsername() + " 修改场次 " + scheduleId + " 的票价");
                        System.out.println("票价修改成功！");
                    }
                } else if (scheduleChoice == 3) {
                    System.out.print("输入场次ID：");
                    String scheduleId = scanner.nextLine();
                    Schedule schedule = scheduleMap.get(scheduleId);
                    if (schedule == null) {
                        System.out.println("场次不存在！");
                        break;
                    }

                    // 校验：该场次是否有售票
                    boolean hasTicket = false;
                    for (TicketOrder order : orderMap.values()) {
                        if (order.getScheduleId().equals(scheduleId)) {
                            hasTicket = true;
                            break;
                        }
                    }
                    if (hasTicket) {
                        System.out.println("场次已有售票，禁止删除！");
                        break;
                    }

                    scheduleMap.remove(scheduleId);
                    logOperation("经理 " + manager.getUsername() + " 删除场次 " + scheduleId);
                    System.out.println("场次删除成功！");
                }
                break;

            case 2:
                System.out.println("=== 销售数据查看 ===");
                System.out.println("1. 日销售数据");
                System.out.println("2. 周销售数据");
                System.out.println("3. 月销售数据");
                int salesChoice = scanner.nextInt();
                scanner.nextLine();

                if (salesChoice == 1) {
                    System.out.print("输入日期（格式：yyyy-MM-dd）：");
                    String dateStr = scanner.nextLine();
                    LocalDateTime date = LocalDateTime.parse(dateStr + " 00:00", java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));

                    double totalAmount = 0;
                    int ticketCount = 0;

                    for (TicketOrder order : orderMap.values()) {
                        Schedule s = scheduleMap.get(order.getScheduleId());
                        if (s.getShowTime().toLocalDate().equals(date.toLocalDate())) {
                            totalAmount += order.getTotalPrice();
                            // 计算票数（根据座位信息格式解析）
                            String[] seats = order.getSeatsInfo().split(";");
                            ticketCount += seats.length;
                        }
                    }

                    System.out.println("日期：" + dateStr);
                    System.out.println("总销售额：" + totalAmount + " 元");
                    System.out.println("总售票数：" + ticketCount + " 张");
                }
                // 周/月数据统计略（逻辑类似）
                break;

            case 3:
                System.out.println("=== 影片信息管理 ===");
                System.out.println("1. 添加影片");
                System.out.println("2. 修改影片");
                System.out.println("3. 删除影片");
                int movieChoice = scanner.nextInt();
                scanner.nextLine();

                if (movieChoice == 1) {
                    System.out.print("输入影片ID：");
                    String movieId = scanner.nextLine();
                    System.out.print("输入影片名称：");
                    String movieName = scanner.nextLine();
                    System.out.print("输入影片导演：");
                    String director= scanner.nextLine();
                    System.out.print("输入影片演员：");
                    String actors = scanner.nextLine();
                    System.out.print("输入影片类型：");
                    String intro = scanner.nextLine();
                    System.out.print("输入影片时长（分钟）：");
                    int duration = scanner.nextInt();
                    System.out.print("输入影片时长（分钟）：");
                    double score = scanner.nextInt();
                    scanner.nextLine();

                    Movie newMovie = new Movie( movieId, movieName,director,actors,intro,duration,score);
                    movieMap.put(movieId, newMovie);

                    logOperation("经理 " + manager.getUsername() + " 添加影片 " + movieId);
                    System.out.println("影片添加成功！");
                } else if (movieChoice == 2) {
                    System.out.print("输入影片ID：");
                    String movieId = scanner.nextLine();
                    Movie movie = movieMap.get(movieId);
                    if (movie == null) {
                        System.out.println("影片不存在！");
                        break;
                    }

                    System.out.println("当前影片信息：");
                    System.out.println("名称：" + movie.getMovieName());
                    System.out.println("类型：" + movie.getIntro());
                    System.out.println("时长：" + movie.getDuration() + " 分钟");

                    System.out.println("1. 修改影片名称");
                    System.out.println("2. 修改影片类型");
                    System.out.println("3. 修改影片时长");
                    System.out.println("4. 修改影片导演");
                    System.out.println("5. 修改影片演员");

                    int modifyChoice = scanner.nextInt();
                    scanner.nextLine();

                    switch (modifyChoice) {
                        case 1:
                            System.out.print("输入新名称：");
                            movie.setMovieName(scanner.nextLine());
                            break;
                        case 2:
                            System.out.print("输入新类型：");
                            movie.setIntro(scanner.nextLine());
                            break;
                        case 3:
                            System.out.print("输入新时长：");
                            movie.setDuration(scanner.nextInt());
                            scanner.nextLine();
                            break;
                        case 4 :
                            System.out.print("输入导演：");
                            movie.setDirector(scanner.nextLine());
                            break;
                        case 5:
                             System.out.print("输入演员：");
                             movie.setActors(scanner.nextLine());
                             break;
                        default:
                            System.out.println("无效选择！");
                            return;
                    }

                    logOperation("经理 " + manager.getUsername() + " 修改影片 " + movieId);
                    System.out.println("影片信息修改成功！");
                } else if (movieChoice == 3) {
                    System.out.print("输入影片ID：");
                    String movieId = scanner.nextLine();
                    if (!movieMap.containsKey(movieId)) {
                        System.out.println("影片不存在！");
                        break;
                    }

                    // 校验：是否有排片
                    boolean hasSchedule = false;
                    for (Schedule s : scheduleMap.values()) {
                        if (s.getMovieId().equals(movieId)) {
                            hasSchedule = true;
                            break;
                        }
                    }
                    if (hasSchedule) {
                        System.out.println("影片已有排片，禁止删除！");
                        break;
                    }

                    // 确认删除
                    System.out.print("删除后无法恢复，确认删除？（y/n）：");
                    if (scanner.nextLine().equals("y")) {
                        movieMap.remove(movieId);
                        logOperation("经理 " + manager.getUsername() + " 删除影片 " + movieId);
                        System.out.println("删除成功！");
                    }
                }
                break;

            case 4:
                System.out.println("=== 密码管理 ===");
                System.out.println("1. 修改自身密码");
                System.out.println("2. 重置前台密码");
                int managerPwdChoice = scanner.nextInt();
                scanner.nextLine();

                if (managerPwdChoice == 1) {
                    System.out.print("输入原密码：");
                    String oldPwd = scanner.nextLine();
                    if (!manager.getPassword().equals(oldPwd)) {
                        System.out.println("原密码错误！");
                        break;
                    }
                    System.out.print("输入新密码：");
                    String newPwd = scanner.nextLine();
                    manager.changePassword(newPwd);
                    logOperation("经理 " + manager.getUsername() + " 修改自身密码");
                    System.out.println("密码修改成功！");
                } else if (managerPwdChoice == 2) {
                    System.out.print("输入要重置密码的前台ID：");
                    String userId = scanner.nextLine();

                    User targetUser = userMap.get(userId);
                    if (targetUser == null) {
                        System.out.println("用户不存在！");
                        break;
                    }

                    if (!targetUser.getUserType().equals("frontdesk")) {
                        System.out.println("该用户不是前台！");
                        break;
                    }

                    System.out.print("输入新密码（默认123456）：");
                    String newPwd = scanner.nextLine();
                    if (newPwd.isEmpty()) newPwd = "123456";

                    targetUser.changePassword(newPwd);
                    targetUser.setFirstLogin(true); // 强制下次登录修改密码
                    logOperation("经理 " + manager.getUsername() + " 重置前台 " + userId + " 的密码");
                    System.out.println("密码重置成功！");
                }
                break;

            default:
                System.out.println("无效选择！");
        }
    }

    private void handleFrontDeskMenu(FrontDesk frontdesk, int choice, Scanner scanner) {
        switch (choice) {
            case 1:
                System.out.println("=== 售票功能 ===");
                System.out.print("输入场次ID：");
                String scheduleId = scanner.nextLine();
                Schedule schedule = scheduleMap.get(scheduleId);
                if (schedule == null) {
                    System.out.println("场次不存在！");
                    break;
                }

                // 显示座位状态
                System.out.println("当前座位状态：");
                Hall hall = hallMap.get(schedule.getHallId());
                char[][] seats = new char[hall.getRowCount()][hall.getColCount()];
                for (int i = 0; i < hall.getRowCount(); i++) {
                    for (int j = 0; j < hall.getColCount(); j++) {
                        seats[i][j] = 'O'; // O表示可选
                    }
                }

                // 标记已售座位
                for (TicketOrder order : orderMap.values()) {
                    if (order.getScheduleId().equals(scheduleId)) {
                        String[] seatPairs = order.getSeatsInfo().split(";");
                        for (String pair : seatPairs) {
                            String[] parts = pair.split(",");
                            int row = Integer.parseInt(parts[0]);
                            int col = Integer.parseInt(parts[1]);
                            seats[row][col] = 'X'; // X表示已售
                        }
                    }
                }

                // 显示座位图
                System.out.print("  ");
                for (int j = 0; j < hall.getColCount(); j++) {
                    System.out.printf("%2d", j);
                }
                System.out.println();

                for (int i = 0; i < hall.getRowCount(); i++) {
                    System.out.printf("%2d", i);
                    for (int j = 0; j < hall.getColCount(); j++) {
                        System.out.printf(" %c", seats[i][j]);
                    }
                    System.out.println();
                }

                // 输入购票座位
                System.out.print("请输入要购买的座位（格式：行号,列号;行号,列号...）：");
                String seatInput = scanner.nextLine();
                String[] seatPairs = seatInput.split(";");

                boolean isValid = true;
                StringBuilder selectedSeats = new StringBuilder();
                double totalPrice = 0;

                for (String pair : seatPairs) {
                    String[] parts = pair.split(",");
                    if (parts.length != 2) {
                        isValid = false;
                        break;
                    }

                    try {
                        int row = Integer.parseInt(parts[0]);
                        int col = Integer.parseInt(parts[1]);

                        if (row < 0 || row >= hall.getRowCount() || col < 0 || col >= hall.getColCount()) {
                            isValid = false;
                            break;
                        }

                        if (seats[row][col] == 'X') {
                            System.out.println("座位 " + row + "," + col + " 已被售出！");
                            isValid = false;
                            break;
                        }

                        if (selectedSeats.length() > 0) {
                            selectedSeats.append(";");
                        }
                        selectedSeats.append(row).append(",").append(col);
                        totalPrice += schedule.getPrice();
                    } catch (NumberFormatException e) {
                        isValid = false;
                        break;
                    }
                }

                if (!isValid) {
                    System.out.println("无效的座位选择！");
                    break;
                }

                // 确认购票
                System.out.println("购票信息：");
                System.out.println("影片：" + movieMap.get(schedule.getMovieId()).getMovieName());
                System.out.println("影厅：" + hall.getHallName());
                System.out.println("时间：" + schedule.getShowTime());
                System.out.println("座位：" + selectedSeats);
                System.out.println("总价：" + totalPrice + " 元");

                System.out.print("确认购买？（y/n）：");
                if (scanner.nextLine().equals("y")) {
                    String orderId = "ORD" + System.currentTimeMillis();
                    TicketOrder order = new TicketOrder(scheduleId, frontdesk.getUserId(),
                            selectedSeats.toString(), totalPrice);
                    orderMap.put(orderId, order);

                    logOperation("前台 " + frontdesk.getUsername() + " 售出票 " + orderId);
                    System.out.println("购票成功！订单号：" + orderId);
                } else {
                    System.out.println("已取消购票！");
                }
                break;

            case 2:
                System.out.println("=== 退票功能 ===");
                System.out.print("输入订单号：");
                String orderId = scanner.nextLine();
                TicketOrder order = orderMap.get(orderId);
                if (order == null) {
                    System.out.println("订单不存在！");
                    break;
                }

                // 校验退票时间（需在电影上映前1小时）
                Schedule s = scheduleMap.get(order.getScheduleId());
                LocalDateTime showTime = s.getShowTime();
                LocalDateTime now = LocalDateTime.now();
                if (now.plusHours(1).isAfter(showTime)) {
                    System.out.println("电影上映前1小时内禁止退票！");
                    break;
                }

                // 确认退票
                System.out.println("退票信息：");
                System.out.println("影片：" + movieMap.get(s.getMovieId()).getMovieName());
                System.out.println("影厅：" + hallMap.get(s.getHallId()).getHallName());
                System.out.println("时间：" + showTime);
                System.out.println("座位：" + order.getSeatsInfo());
                System.out.println("退款金额：" + order.getTotalPrice() + " 元");

                System.out.print("确认退票？（y/n）：");
                if (scanner.nextLine().equals("y")) {
                    orderMap.remove(orderId);
                    logOperation("前台 " + frontdesk.getUsername() + " 退回订单 " + orderId);
                    System.out.println("退票成功！");
                } else {
                    System.out.println("已取消退票！");
                }
                break;

            case 3:
                System.out.println("=== 场次座位查询 ===");
                System.out.print("输入场次ID：");
                String queryScheduleId = scanner.nextLine();
                Schedule querySchedule = scheduleMap.get(queryScheduleId);
                if (querySchedule == null) {
                    System.out.println("场次不存在！");
                    break;
                }

                // 显示座位状态（逻辑同售票功能）
                System.out.println("影片：" + movieMap.get(querySchedule.getMovieId()).getMovieName());
                System.out.println("影厅：" + hallMap.get(querySchedule.getHallId()).getHallName());
                System.out.println("时间：" + querySchedule.getShowTime());
                System.out.println("当前座位状态：");

                Hall queryHall = hallMap.get(querySchedule.getHallId());
                char[][] querySeats = new char[queryHall.getRowCount()][queryHall.getColCount()];
                for (int i = 0; i < queryHall.getRowCount(); i++) {
                    for (int j = 0; j < queryHall.getColCount(); j++) {
                        querySeats[i][j] = 'O';
                    }
                }

                for (TicketOrder o : orderMap.values()) {
                    if (o.getScheduleId().equals(queryScheduleId)) {
                        seatPairs = o.getSeatsInfo().split(";");
                        for (String pair : seatPairs) {
                            String[] parts = pair.split(",");
                            int row = Integer.parseInt(parts[0]);
                            int col = Integer.parseInt(parts[1]);
                            querySeats[row][col] = 'X';
                        }
                    }
                }

                // 显示座位图（逻辑同售票功能）
                System.out.print("  ");
                for (int j = 0; j < queryHall.getColCount(); j++) {
                    System.out.printf("%2d", j);
                }
                System.out.println();

                for (int i = 0; i < queryHall.getRowCount(); i++) {
                    System.out.printf("%2d", i);
                    for (int j = 0; j < queryHall.getColCount(); j++) {
                        System.out.printf(" %c", querySeats[i][j]);
                    }
                    System.out.println();
                }

                // 计算剩余票数
                int availableSeats = 0;
                for (int i = 0; i < queryHall.getRowCount(); i++) {
                    for (int j = 0; j < queryHall.getColCount(); j++) {
                        if (querySeats[i][j] == 'O') {
                            availableSeats++;
                        }
                    }
                }

                System.out.println("剩余票数：" + availableSeats + " / " + (queryHall.getRowCount() * queryHall.getColCount()));
                break;

            case 4:
                System.out.println("=== 影片信息查询（正在上映） ===");
                LocalDateTime nowTime = LocalDateTime.now();

                // 收集正在上映的影片ID
                Set<String> showingMovieIds = new HashSet<>();
                for (Schedule sch : scheduleMap.values()) {
                    if (sch.getShowTime().isAfter(nowTime)) {
                        showingMovieIds.add(sch.getMovieId());
                    }
                }

                if (showingMovieIds.isEmpty()) {
                    System.out.println("暂无正在上映的影片！");
                    break;
                }

                System.out.println("正在上映的影片：");
                for (String movieId : showingMovieIds) {
                    Movie movie = movieMap.get(movieId);
                    System.out.println("ID：" + movieId + "，名称：" + movie.getMovieName()
                            + "，类型：" + movie.getIntro()
                            + "，时长：" + movie.getDuration() + "分钟");

                    // 显示该影片的场次
                    System.out.println("  场次信息：");
                    for (Schedule sch : scheduleMap.values()) {
                        if (sch.getMovieId().equals(movieId) && sch.getShowTime().isAfter(nowTime)) {
                            System.out.println("  - 场次ID：" + sch.getScheduleId()
                                    + "，时间：" + sch.getShowTime()
                                    + "，影厅：" + hallMap.get(sch.getHallId()).getHallName()
                                    + "，票价：" + sch.getPrice());
                        }
                    }
                }
                break;

            case 5:
                System.out.println("=== 场次信息查询 ===");
                System.out.println("1. 当日场次");
                System.out.println("2. 3日内场次");
                System.out.println("3. 1周内场次");
                int timeChoice = scanner.nextInt();
                scanner.nextLine();

                LocalDateTime startTime = LocalDateTime.now();
                LocalDateTime endTime;

                switch (timeChoice) {
                    case 1:
                        endTime = startTime.plusDays(1);
                        break;
                    case 2:
                        endTime = startTime.plusDays(3);
                        break;
                    case 3:
                        endTime = startTime.plusDays(7);
                        break;
                    default:
                        System.out.println("无效选择！");
                        return;
                }

                boolean hasSchedules = false;
                for (Schedule sch : scheduleMap.values()) {
                    if (sch.getShowTime().isAfter(startTime) && sch.getShowTime().isBefore(endTime)) {
                        hasSchedules = true;
                        System.out.println("场次ID：" + sch.getScheduleId());
                        System.out.println("  影片：" + movieMap.get(sch.getMovieId()).getMovieName());
                        System.out.println("  时间：" + sch.getShowTime());
                        System.out.println("  影厅：" + hallMap.get(sch.getHallId()).getHallName());
                        System.out.println("  票价：" + sch.getPrice());

                        // 计算剩余票数
                        Hall h = hallMap.get(sch.getHallId());
                        int totalSeats = h.getRowCount() * h.getColCount();
                        int soldSeats = 0;

                        for (TicketOrder o : orderMap.values()) {
                            if (o.getScheduleId().equals(sch.getScheduleId())) {
                                soldSeats += o.getSeatsInfo().split(";").length;
                            }
                        }

                        System.out.println("  剩余票数：" + (totalSeats - soldSeats) + " / " + totalSeats);
                    }
                }

                if (!hasSchedules) {
                    System.out.println("此时间段暂无场次！");
                }
                break;

            case 6:
                System.out.println("=== 修改自身密码 ===");
                System.out.print("输入原密码：");
                String oldPwd = scanner.nextLine();
                if (!frontdesk.getPassword().equals(oldPwd)) {
                    System.out.println("原密码错误！");
                    break;
                }
                System.out.print("输入新密码：");
                String newPwd = scanner.nextLine();
                frontdesk.changePassword(newPwd);
                logOperation("前台 " + frontdesk.getUsername() + " 修改自身密码");
                System.out.println("密码修改成功！");
                break;

            default:
                System.out.println("无效选择！");
        }
    }

    private void printUserInfo(User user) {
        System.out.println("ID：" + user.getUserId()
                + "，用户名：" + user.getUsername()
                + "，类型：" + user.getUserType()
                + "，注册时间：" + user.getRegisterTime()
                + "，手机号：" + user.getPhone());
    }

    // 日志记录（写入文件）
    private void logOperation(String log) {
        String logInfo = LocalDateTime.now() + " - " + log;
        logList.add(logInfo);
        // 写入文件（追加模式）
        try (PrintWriter out = new PrintWriter(new FileWriter("system_log.txt", true))) {
            out.println(logInfo);
        } catch (IOException e) {
            System.out.println("日志写入失败：" + e.getMessage());
        }
    }

    public static void main(String[] args) {
        CinemaSystem system = new CinemaSystem();
        system.startSystem();
    }
}